import React, { useState } from 'react';
import {
  Box,
  Button,
  TextField,
  Paper,
  Typography,
  Chip,
  IconButton,
  useTheme,
} from '@mui/material';
import { motion } from 'framer-motion';
import AddIcon from '@mui/icons-material/Add';
import { usePost } from '../contexts/PostContext';
import { useAuth } from '../../auth/AuthContext';

const PostForm: React.FC = () => {
  const theme = useTheme();
  const { createPost } = usePost();
  const { user } = useAuth();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [tag, setTag] = useState('');
  const [tags, setTags] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleAddTag = () => {
    if (tag.trim() && !tags.includes(tag.trim())) {
      setTags([...tags, tag.trim()]);
      setTag('');
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setTags(tags.filter((t) => t !== tagToRemove));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user || !title.trim() || !content.trim()) return;

    try {
      setIsSubmitting(true);
      // 注意：这里传递的参数顺序是 content, title，与 PostService 中的参数顺序一致
      await createPost(content, title);
      setTitle('');
      setContent('');
      setTags([]);
    } catch (error) {
      console.error('发布帖子失败:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Paper
      component={motion.form}
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
      elevation={3}
      sx={{
        p: 3,
        mb: 4,
        borderRadius: 2,
        background: theme.palette.background.paper,
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
      }}
      onSubmit={handleSubmit}
    >
      <Typography
        variant="h6"
        gutterBottom
        sx={{
          fontWeight: 600,
          color: theme.palette.primary.main,
          mb: 3
        }}
      >
        发布新帖
      </Typography>

      <TextField
        fullWidth
        label="标题"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        required
        sx={{ mb: 3 }}
      />

      <TextField
        fullWidth
        label="内容"
        value={content}
        onChange={(e) => setContent(e.target.value)}
        required
        multiline
        rows={4}
        sx={{ mb: 3 }}
      />

      <Box sx={{ mb: 3 }}>
        <Box sx={{ display: 'flex', gap: 1, mb: 2 }}>
          <TextField
            label="添加标签"
            value={tag}
            onChange={(e) => setTag(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddTag())}
            size="small"
          />
          <IconButton
            onClick={handleAddTag}
            color="primary"
            sx={{ minWidth: 'auto' }}
          >
            <AddIcon />
          </IconButton>
        </Box>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
          {tags.map((tag) => (
            <Chip
              key={tag}
              label={tag}
              onDelete={() => handleRemoveTag(tag)}
              color="primary"
              variant="outlined"
              size="small"
            />
          ))}
        </Box>
      </Box>

      <Button
        type="submit"
        variant="contained"
        color="primary"
        disabled={isSubmitting || !title.trim() || !content.trim()}
        fullWidth
      >
        {isSubmitting ? '发布中...' : '发布'}
      </Button>
    </Paper>
  );
};

export default PostForm;